package test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class AccessPersonConstructors {
    public static void main(String[] args) {
        try {
            // 加载Person类
            Class clz = Class.forName("entity.Person");

            // 获取Person 的无参构造,public Person()
            Constructor c1 = clz.getDeclaredConstructor();

            // 调用Person类对的无参构造创建Person类实例
            Object obj = c1.newInstance();
            // 调用Person实例的toString()方法，属性均为默认值
            System.out.println(obj);


            // 获取Person的单参构造: private Person(String)
            Constructor c2 = clz.getDeclaredConstructor(String.class);
            // person 的单参数构造为Private,这里已超出其访问范围，不能直接访问
            // 通过setAccessible方法，设定为可以访问
            c2.setAccessible(true);
            obj = c2.newInstance("new Person");
            System.out.println(obj);



            // 获取Person的单参构造: private Person(String)
            Constructor c3 = clz.getDeclaredConstructor(String.class, String.class,String.class);

            // Person 的三参构造为Protected,这里已超出其他访问范围,不能直接访问
            // 通过setAccessable 方法，设定为可以访问
            c3.setAccessible(true);

            obj = c3.newInstance("New Person", "beijinng", "Hello！");
            System.out.println(obj);

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } finally {
        }
    }
}
